package com.zelin.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zelin.gulimall.product.entity.CategoryBrandRelationEntity;
import com.zelin.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelin.common.utils.PageUtils;
import com.zelin.common.utils.Query;

import com.zelin.gulimall.product.dao.BrandDao;
import com.zelin.gulimall.product.entity.BrandEntity;
import com.zelin.gulimall.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(key)){
            queryWrapper.eq("brand_id",key)
                        .or()
                        .like("name",key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    //级联更新Brand表与中间表
    @Override
    public void updateDetail(BrandEntity brand) {
        //1. 更新自身
        updateById(brand);
        //2. 更新brandCategory中间表
        CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
        entity.setBrandId(brand.getBrandId());
        entity.setBrandName(brand.getName());
        UpdateWrapper<CategoryBrandRelationEntity> updateWarpper
                = new UpdateWrapper<>();
        updateWarpper.eq("brand_id",brand.getBrandId());
        categoryBrandRelationService.update(entity,updateWarpper);
    }

}